package com.yimi.yinhepda.db.dao;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.stmt.QueryBuilder;
import com.yimi.yinhepda.base.BaseApplication;
import com.yimi.yinhepda.db.helper.DbHelper;
import com.yimi.yinhepda.db.table.CompanyTable;
import com.yimi.yinhepda.entity.response.CompanyInfo;
import com.pda.uce.commom.util.LogUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created on 2017/4/19
 *
 * @author 000432
 */
public class CompanyTableDao extends BaseDao<CompanyTable, Long> {

    public CompanyTableDao() {
        super(DbHelper.getInstance(BaseApplication.getContext()), CompanyTable.class);
    }

    public List<CompanyTable> findCompCode(String compCode) {
        try {
            QueryBuilder<CompanyTable, Long> queryBuilder = dao.queryBuilder();
            List<CompanyTable> departmentTableList = queryBuilder.where().like("compCode", compCode).query();
            return departmentTableList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String findOrderByLatestTime() {
        String lastTime = null;
        try {
            QueryBuilder<CompanyTable, Long> queryBuilder = dao.queryBuilder().orderBy("lastTime", false).limit(1L);
            List<CompanyTable> list = queryBuilder.query();
            if (list != null && list.size() > 0) {
                lastTime = list.get(0).getLastTime();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return lastTime;
    }

    public void createOrUpdate(List<CompanyInfo> list) {
        SQLiteDatabase database = getDbHelper().getWritableDatabase();
        String tableName = dao.getTableName();
        StringBuffer sql = new StringBuffer("replace into ");
        sql.append(tableName);
        sql.append("(companyId,");
        sql.append("compCode,");
        sql.append("longName,");
        sql.append("shortName,");
        sql.append("telephone,");
        sql.append("fax,");
        sql.append("mobile,");
        sql.append("allowMsg,");
        sql.append("address,");
        sql.append("legalPerson,");
        sql.append("state,");
        sql.append("menuTempId,");
        sql.append("compType,");
        sql.append("settlementEentity,");
        sql.append("belongCompany,");
        sql.append("compLogo,");
        sql.append("compPwd,");
        sql.append("modifierTime,");
        sql.append("modifier,");
        sql.append("isDelete,");
        sql.append("lastTime,");
        sql.append("recordVersion,");
        sql.append("incorrect,");
        sql.append("arbitration,");
        sql.append("claims)");
        //25
        sql.append("values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
        LogUtil.e("sql=" + sql.toString());

        database.beginTransaction();
        for (CompanyInfo item : list) {
            Object[] values = new Object[]{
                    item.getCompany_id(), item.getComp_code(), item.getLong_name(), item.getShort_name(), item.getTelephone(), item.getFax(), item.getMobile(),
                    item.getAllow_msg(), item.getAddress(), item.getLegal_person(), item.getState(), item.getMenu_temp_id(), item.getComp_type(),
                    item.getSettlement_entity(), item.getBelong_company(), item.getComp_logo(), item.getComp_pwd(), item.getModifier_time(), item.getModifier(),
                    item.getIs_delete(), item.getLatest_time(), item.getRecord_version(), item.getIncorrect(), item.getArbitration(), item.getClaims()
            };
            database.execSQL(sql.toString(), values);
        }
        database.setTransactionSuccessful();
        database.endTransaction();
    }

    public CompanyTable findCompCodeDate(String compCode) {
        try {
            QueryBuilder<CompanyTable, Long> queryBuilder = dao.queryBuilder();
            return queryBuilder.where().like("compCode", compCode).queryForFirst();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 分页查询数据
     */
    public List<CompanyTable> queryDataByPage(long currentPage, long pageSize) {
        try {
            QueryBuilder<CompanyTable, Long> queryBuilder = dao.queryBuilder();
            return queryBuilder.offset(currentPage).limit(pageSize).query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据sql语句查询
     *
     * @param sql sql语句
     * @return list
     */
    public List<CompanyTable> queryDataBySql(String sql) {
        SQLiteDatabase database = getDbHelper().getWritableDatabase();
        List<CompanyTable> list = new ArrayList<>();
        Cursor cursor = database.rawQuery(sql, null);
        if (cursor != null && cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                CompanyTable table = new CompanyTable();
                int id = cursor.getColumnIndex("id");
                if (id == 0) {
                    table.setId(cursor.getLong(id));
                }
                table.setCompanyId(cursor.getString(cursor.getColumnIndex("companyId")));
                table.setCompCode(cursor.getString(cursor.getColumnIndex("compCode")));
                table.setLongName(cursor.getString(cursor.getColumnIndex("longName")));
                table.setShortName(cursor.getString(cursor.getColumnIndex("shortName")));
                table.setTelephone(cursor.getString(cursor.getColumnIndex("telephone")));
                table.setFax(cursor.getString(cursor.getColumnIndex("fax")));
                table.setMobile(cursor.getString(cursor.getColumnIndex("mobile")));
                table.setAllowMsg(cursor.getInt(cursor.getColumnIndex("allowMsg")));
                table.setAddress(cursor.getString(cursor.getColumnIndex("address")));
                table.setLegalPerson(cursor.getString(cursor.getColumnIndex("legalPerson")));
                table.setState(cursor.getInt(cursor.getColumnIndex("state")));
                table.setMenuTempId(cursor.getString(cursor.getColumnIndex("menuTempId")));
                table.setCompType(cursor.getInt(cursor.getColumnIndex("compType")));
                table.setSettlementEentity(cursor.getInt(cursor.getColumnIndex("settlementEentity")));
                table.setBelongCompany(cursor.getInt(cursor.getColumnIndex("belongCompany")));
                table.setCompLogo(cursor.getString(cursor.getColumnIndex("compLogo")));
                table.setCompPwd(cursor.getString(cursor.getColumnIndex("compPwd")));
                table.setModifierTime(cursor.getString(cursor.getColumnIndex("modifierTime")));
                table.setModifier(cursor.getString(cursor.getColumnIndex("modifier")));
                table.setIsDelete(cursor.getInt(cursor.getColumnIndex("isDelete")));
                table.setLastTime(cursor.getString(cursor.getColumnIndex("lastTime")));
                table.setRecordVersion(cursor.getInt(cursor.getColumnIndex("recordVersion")));
                table.setIncorrect(cursor.getInt(cursor.getColumnIndex("incorrect")));
                table.setArbitration(cursor.getInt(cursor.getColumnIndex("arbitration")));
                table.setClaims(cursor.getInt(cursor.getColumnIndex("claims")));
                list.add(table);
            }
            cursor.close();
        }
        return list;
    }
}
